package com.bolt.admin.module.email.service;

import com.bolt.admin.module.email.dto.EmailConfigDTO;
import com.bolt.admin.module.email.dto.converter.EmailConfigConverter;
import com.bolt.admin.module.email.entity.EmailConfigEntity;
import com.bolt.admin.module.email.repository.EmailConfigRepository;
import com.bolt.common.collection.IteratorUtil;
import com.bolt.common.mail.MailAccount;
import com.bolt.common.mail.MailSender;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.exception.ServiceException;
import com.bolt.support.base.service.BaseService;
import com.bolt.support.spring.jpa.filter.FilterBuilder;
import com.bolt.support.spring.jpa.repository.BasicJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Auto Generate Javadoc
 *
 * @author 日期:2020-10-12 11:34:11
 *         邮箱配置
 **/
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class EmailService extends BaseService <EmailConfigEntity, Long> {

    @Autowired
    private EmailConfigRepository configRepository;

    @Override
    protected BasicJpaRepository <EmailConfigEntity, Long> getRepository() {
        return configRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(EmailConfigDTO dto) {
        EmailConfigEntity entity = EmailConfigConverter.toEntity(dto);
        save(entity);
    }

    public EmailConfigEntity findDefault() {
        List <EmailConfigEntity> entities = this.findLimit((FilterBuilder <EmailConfigEntity> f) ->
                        f.lambda().eq(EmailConfigEntity::getGlobal, true).build()
                , null, 1);
        if (IteratorUtil.isEmpty(entities)) {
            throw new ServiceException("请先配置，再操作");
        } else {
            return entities.get(0);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void send(String to, String subject, String content) {

        if (StrUtil.isBlank(to)) {
            throw new ServiceException("收件人不能为空");
        }

        if (StrUtil.isBlank(subject)) {
            throw new ServiceException("邮件标题不能为空");
        }

        if (StrUtil.isBlank(content)) {
            throw new ServiceException("内容不能为空");
        }

        EmailConfigEntity emailConfig = findDefault();
        // 封装
        MailAccount account = new MailAccount();
        account.setUser(emailConfig.getUser());
        account.setHost(emailConfig.getHost());
        account.setPort(Integer.parseInt(emailConfig.getPort()));
        account.setAuth(true);

        account.setPass(emailConfig.getPass());

        account.setFrom(emailConfig.getUser() + "<" + emailConfig.getFromUser() + ">");
        // ssl方式发送
        account.setSslEnable(false);
        // 使用STARTTLS安全连接
        account.setStarttlsEnable(false);
        // 发送
        try {
            MailSender.create(account)
                    .setTos(to)
                    .setTitle(subject)
                    .setContent(content)
                    .setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false)
                    .send();
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
